package utils

import (
	"time"

	"gitee.com/sansaniot/ssiot-core/logger"
	"gorm.io/gorm"
)

// 分组名
func GroupIdName(tx *gorm.DB, deptIdQuery ...[]string) (mp map[string]string, err error) {
	mp = make(map[string]string)
	deptList := make([]Dept, 0)
	if len(deptIdQuery) > 0 {
		err = (Dept{}).FindListByConds(tx, &deptList, "id in (?)", deptIdQuery[0])
	} else {
		err = (Dept{}).FindList(tx, &deptList)
	}
	if err != nil {
		logger.Error(err)
		return mp, err
	}
	for _, v := range deptList {
		mp[v.Id] = v.Name
	}
	return mp, nil
}

type Dept struct {
	Id            string    `json:"id" gorm:"primaryKey"`
	ParentId      string    `json:"parentId"`
	Name          string    `json:"name"`
	OrderNum      int32     `json:"orderNum"`
	CreateTimeDts time.Time `json:"-"`
	CreateTime    string    `json:"createTime" gorm:"-"`
	UpdateTimeDts time.Time `json:"-"`
	UpdateTime    string    `json:"updateTime" gorm:"-"`
	CreatorId     string    `json:"creatorId"`
	Creator       string    `json:"creator"`
}

func (Dept) FindList(db *gorm.DB, data interface{}, condition ...func(db *gorm.DB) *gorm.DB) (err error) {
	err = db.Model(&Dept{}).
		Scopes(
			condition...,
		).
		Find(data).
		Limit(-1).Offset(-1).Error
	return err
}

func (Dept) FindListByConds(db *gorm.DB, data interface{}, conds string, params ...interface{}) (err error) {
	return db.Model(&Dept{}).Where(conds, params...).Find(data).Error
}

func (Dept) TableName() string {
	return "sys_dept"
}
